<template>
  <el-card>
    <el-form
      ref="addForm"
      label-width="100px"
      :model="specsData"
      :rules="rules"
    >
      <el-form-item label="属性名" prop="specsname">
        <el-input
          placeholder="请输入属性名"
          v-model="specsData.specsname"
        ></el-input>
      </el-form-item>
      <el-form-item label="属性值" prop="attrs">
        <div
          class="attr-item"
          v-for="(item, index) in specsData.attrs"
          :key="index"
        >
          <el-input
            v-model.trim="specsData.attrs[index]"
            placeholder="请输入属性值"
          ></el-input>
          <el-button v-if="index === 0" @click="addItem" type="success"
            >新增</el-button
          >
          <el-button v-else @click="delItem(index)" type="danger"
            >删除</el-button
          >
        </div>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="specsData.status">
          <el-radio :label="1">正常</el-radio>
          <el-radio :label="2">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">立即提交</el-button>
        <el-button type="default" @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
export default {
  data() {
    const validAttrs = (rule, value, callback) => {
      this.specsData.attrs.forEach((item) => {
        if (item === "") {
          callback(new Error("请输入属性值"));
        }
      });
      callback();
    };
    return {
      specsData: {
        specsname: "",
        attrs: [""],
        status: 1,
      },
      rules: {
        specsname: {required: true,message: "请输入属性名",},
        attrs: { validator: validAttrs, trigger: "blur" },
        status: { required: true, message: "请选择状态" },
      },
    };
  },
  methods: {
    submitForm() {
      this.$refs.addForm.validate(async (valid) => {
        if (valid) {
          this.specsData.attrs = this.specsData.attrs.join(",");
          const res = await this.$http.post("/api/specsadd", this.specsData);
          if (res.code == 200) {
            this.$success(res.msg);
            return this.$router.push("/specs");
          }
          this.$error(res.msg);
        }
      });
    },
    resetForm() {
      this.$refs.addForm.resetFields();
    },
    delItem(index) {
      this.specsData.attrs.splice(index, 1);
    },
    addItem() {
      if (this.specsData.attrs.length >= 5) {
        return this.$error("最多只能添加5个属性值");
      }
      this.specsData.attrs.push("");
    },
  },
};
</script>

<style lang="less" scoped>
.el-form {
  width: 600px;
  margin: auto;
}
.attr-item {
  display: flex;
  justify-content: space-between;
  margin: 5px 0;
  .el-input {
    width: 400px;
  }
}
</style>